package co.baiku.boot.wechat.config.ma;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceHttpClientImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import co.baiku.boot.wechat.enums.HttpClientType;
import co.baiku.boot.wechat.properties.WxMaProperties;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 微信小程序平台相关服务自动注册.
 *
 * @author someone TaoYu
 */
@Configuration
@AllArgsConstructor
@ConditionalOnProperty(prefix = "wx.miniapp", value = "enabled", havingValue = "true")
public class WxMaServiceAutoConfiguration {

    private final WxMaProperties wxMaProperties;

    /**
     * 小程序service.
     *
     * @return 小程序service
     */
    @Bean
    @ConditionalOnMissingBean(WxMaService.class)
    @ConditionalOnBean(WxMaConfig.class)
    public WxMaService wxMaService(WxMaConfig wxMaConfig) {
        HttpClientType httpClientType = wxMaProperties.getConfigStorage().getHttpClientType();
        WxMaService wxMaService;
        switch (httpClientType) {
            case HttpClient:
                wxMaService = new WxMaServiceHttpClientImpl();
                break;
            default:
                wxMaService = new WxMaServiceImpl();
                break;
        }
        wxMaService.setWxMaConfig(wxMaConfig);
        return wxMaService;
    }
}
